package org.xlx.xlx_oa.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.unit.DataSize;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class FileUpLoad {
    @Value("${spring.servlet.multipart.max-file-size:3MB}")
    private DataSize maxFileSize;

    public String upload(MultipartFile file) throws Exception {
        if (file.getSize() > maxFileSize.toBytes()) {
            throw new Exception("file too large");
        }
        InputStream inputStream = file.getInputStream();
        String relativePath = null;
        //判断上传文件格式
        String fileType = file.getContentType();
        if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpg")) {
            // 要上传的目标文件存放的绝对路径
            final String localPath = Constant.ICON_LOCATION + "\\" + Constant.USERID;
            File imageDict = new File(localPath);
            if (!imageDict.exists()) {
                imageDict.mkdirs();
            }
            //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
            //获取文件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀名
            assert fileName != null;
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //重新生成文件名
            fileName = UUID.randomUUID() + suffixName;
            if (this.uploadValidate(file, localPath, fileName)) {
                relativePath = Constant.USERID + "/" + fileName;
            } else {
                throw new Exception("file upload failed");
            }
        } else {
            throw new Exception("file type error");
        }
        return relativePath;
    }

    public boolean uploadValidate(MultipartFile file, String path, String fileName) {

        //确定上传的文件名
        String realPath = path + "\\" + fileName;
        File dest = new File(realPath);

        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

}
